package hk.m4s.lr.repair.test.ui.anount;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import framework.common.Constant;
import framework.common.baseui.UeBaseActivity;
import framework.common.runtimepermissions.PermissionsManager;
import framework.common.runtimepermissions.PermissionsResultAction;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.AccountModel;
import hk.m4s.lr.repair.test.model.VcodeModel;
import hk.m4s.lr.repair.test.service.AccountSerive;
import hk.m4s.lr.repair.test.ui.MainActivity;
import hk.m4s.lr.repair.test.utils.ShareUtil;
import hk.m4s.lr.repair.test.utils.SharedPreferencesUtil;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/21.
 * 登录
 */

public class LoginActivity extends UeBaseActivity implements View.OnClickListener {
    private EditText username, password;
    private Button login, regsit_btn;
    private TextView forgetpwd_btn, login_check;
    private int check = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_login);
        hiddenFooter();
        hiddenGoBackBtn();
        setTitleText("左右维修企业");
        requestPermissions();
        SharedPreferencesUtils.addgetSharedPreferences(Constant.check, String.valueOf(check));
        initView();
    }

    private void initView() {
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.login);
        login.setOnClickListener(this);
        regsit_btn = (Button) findViewById(R.id.regist);
        regsit_btn.setOnClickListener(this);
        forgetpwd_btn = (TextView) findViewById(R.id.forgetpwd_btn);
        forgetpwd_btn.setOnClickListener(this);
        login_check = (TextView) findViewById(R.id.login_check);
        login_check.setOnClickListener(this);
        if (!(SharedPreferencesUtils.getSharedPreferences(Constant.phoneNum, "") == null || SharedPreferencesUtils.getSharedPreferences(Constant.phoneNum, "").equals(""))) {
            username.setText(SharedPreferencesUtils.getSharedPreferences(Constant.phoneNum, ""));
        }
        username.addTextChangedListener(new phoneNoTextWatcher(
                username) {

            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                String usernameVal = username.getText().toString().replace(" ", "");
                String pwd = password.getText().toString();
                if (TextUtils.isEmpty(usernameVal)) {
                    ToastUtil.toast(this, "账号不能为空");
                    return;
                } else if (usernameVal.length() < 11) {
                    ToastUtil.toast(this, "请输入正确的手机号");
                    return;
                } else if (TextUtils.isEmpty(pwd)) {
                    ToastUtil.toast(this, "密码不能为空");
                    return;
                }
                if (SharedPreferencesUtils.getSharedPreferences("if_share", "") != null) {
                    if (SharedPreferencesUtils.getSharedPreferences("if_share", "").equals("-1")) {
                        login.setText("分享后登录");
                        ShareUtil.showShare(LoginActivity.this, usernameVal, "左右-维修", SharedPreferencesUtils.getSharedPreferences("shareUrl", ""), "左右-维修", null);
                    } else {
                        login.setText("登录");
                        login(usernameVal, pwd);
                    }
                } else {
                    login.setText("登录");
                    login(usernameVal, pwd);
                }

                break;
            case R.id.regist:
                Intent startRegist = new Intent(this, RegistActivity.class);
                startActivity(startRegist);
                break;
            case R.id.forgetpwd_btn:
                Intent startForgetPwd = new Intent(this, ForgetPassActivity.class);
                startActivity(startForgetPwd);
                break;
            case R.id.login_check:
                if (check == 1) {
                    check = 0;
                    SharedPreferencesUtils.addgetSharedPreferences(Constant.check, String.valueOf(check));
                    Drawable drawable = getResources().getDrawable(R.mipmap.select_no);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    login_check.setCompoundDrawables(drawable, null, null, null);
                } else {
                    check = 1;
                    SharedPreferencesUtils.addgetSharedPreferences(Constant.check, String.valueOf(check));
                    Drawable drawable = getResources().getDrawable(R.mipmap.select_yes);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    login_check.setCompoundDrawables(drawable, null, null, null);
                }
                break;
        }
    }

    private void jumpToMain() {
        Intent startMain = new Intent(this, MainActivity.class);
        startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
        ShareUtil.shareFlag = -1;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ShareUtil.shareFlag != -1) {
            login.setText("登录");
            login(username.getText().toString().replace(" ", ""), password.getText().toString());
        }
    }

    public void login(final String usernameVal, String pass) {

        AccountSerive.login(this, usernameVal, pass, new ResponseCallback<AccountModel>() {
            @Override
            public void onSuccess(AccountModel map) {
                if (map.getIf_share().equals("-1")) {
                    login.setText("分享后登录");
                    SharedPreferencesUtils.addgetSharedPreferences("shareUrl", map.getUrl());
                    ShareUtil.showShare(LoginActivity.this, usernameVal, "左右-维修", map.getUrl(), "左右-维修", null);
                } else {
                    SharedPreferencesUtils.addgetSharedPreferences("if_share", map.getIf_share());
                    SharedPreferencesUtil.getInstance().putString("members_id", map.getMembers_id());
                    SharedPreferencesUtils.addgetSharedPreferences(Constant.phoneNum, map.getTel());
                    SharedPreferencesUtils.addgetSharedPreferences(Constant.token, map.getToken());
                    SharedPreferencesUtils.addgetSharedPreferences(Constant.userId, map.getId());
                    SharedPreferencesUtils.addgetSharedPreferences(Constant.ifadmin, map.getRole());
                    jumpToMain();
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }
}
